const colors = require('colors');
const { STATUS_CODE } = require('../constants');
const dbService = require('../service/dbService');
const momentService = require('../service/moment');
class MomentController {
  async create(ctx) {
    const moment = ctx.request.body;
    const { user } = ctx;
    const result = await dbService.insert(
      {
        ...moment,
        user_id: user.id,
      },
      'moment'
    );
    if (result.insertId) {
      ctx.makeResp({
        code: STATUS_CODE.SUCCESS,
        message: 'success',
      });
    }
  }
  async getMomentDetailById(ctx) {
    const { id } = ctx.request.params;
    try {
      const result = await momentService.getMomentDetailById(id);
      ctx.makeResp({
        code: STATUS_CODE.SUCCESS,
        data: result[0] || {},
        message: 'success',
      });
    } catch (error) {
      console.log(error);
    }
  }
  async getMomentList(ctx) {
    const params = ctx.query;
    try {
      const result = await momentService.getMomentList(params);
      ctx.makeResp({
        code: STATUS_CODE.SUCCESS,
        data: result || {},
        message: 'success',
      });
    } catch (error) {
      console.log(error);
    }
  }
  async updateMoment(ctx) {
    const { content, id } = ctx.request.body;
    const user_id = ctx.user.id;
    const result = await dbService.update({ content }, { id, user_id }, 'moment');
    if (result) {
      ctx.makeResp({});
    }
  }
  async deleteMoment(ctx) {
    const { id } = ctx.params;
    const result = await dbService.delete({ id }, 'moment');
    if (result) {
      ctx.makeResp({ message: 'delete success' });
    }
  }

  async addLabels(ctx) {
    const { id, labels } = ctx.request.body;
    const dbLabels = await momentService.queryAndCreateLabels(labels);
    // 将动态和标签进行映射
    try {
      for (const item of dbLabels) {
        const condition = {
          label_id: item.id,
          moment_id: id,
        };
        const db = 'moment_label';
        const result = await dbService.query(condition, db);
        console.log(
          `debug log：add moment label --- ${item.name} --- exist?：${result && result.length} --- insert?:${!(
            result && result.length
          )}`.green
        );
        if (!(result && result.length)) {
          await dbService.insert(condition, db);
        }
      }
    } catch (error) {
      ctx.makeResp({ code: STATUS_CODE.ERROR });
    }
    ctx.makeResp({ message: 'add labels success~' });
  }
}

module.exports = new MomentController();
